/**
 * @file data_dispatcher.c
 * @brief 消息分发器实现
 * @details 实现从IoT平台数据到不同协议的消息分发逻辑
 */

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <pthread.h>
#include "../include/data_dispatcher.h"
#include "../../../common/json/include/json_utils.h"
#include "../../../common/logs/include/logger.h"

#define LOG_MODULE_NAME "DATA_DISPATCHER"

/* ==================== 内部数据结构 ==================== */

/**
 * @brief 分发器内部数据
 */
typedef struct {
    dispatcher_config_t config;         /* 配置 */
    void* adapter_handles[DISPATCH_PROTOCOL_MAX];  /* 适配器句柄数组 */
    pthread_mutex_t mutex;              /* 互斥锁 */
} dispatcher_private_t;

/* ==================== 辅助函数 ==================== */

/**
 * @brief 简单的字符串匹配（支持通配符*）
 */
static bool match_pattern(const char* str, const char* pattern) {
    if (str == NULL || pattern == NULL) {
        return false;
    }
    
    // 完全匹配
    if (strcmp(str, pattern) == 0) {
        return true;
    }
    
    // 通配符匹配（简单实现）
    if (strstr(pattern, "*") != NULL) {
        // TODO: 实现更完善的通配符匹配
        return strstr(str, pattern) != NULL;
    }
    
    return false;
}

/**
 * @brief 从JSON中提取字符串值
 */
static const char* extract_json_string(void* json_obj, const char* key) {
    if (json_obj == NULL || key == NULL) {
        return NULL;
    }
    
    void* item = json_utils_get_object_item(json_obj, key);
    if (item == NULL) {
        return NULL;
    }
    
    return json_utils_get_string_value(item);
}

/**
 * @brief 匹配路由规则
 */
static dispatch_protocol_type_t match_route(dispatcher_private_t* dispatcher, void* json_obj) {
    if (dispatcher == NULL || json_obj == NULL) {
        return DISPATCH_PROTOCOL_MAX;
    }
    
    // 按优先级排序规则（优先级小的先匹配）
    route_rule_t sorted_rules[64];
    uint32_t rule_count = dispatcher->config.rule_count;
    if (rule_count > 64) {
        rule_count = 64;
    }
    
    // 复制规则
    for (uint32_t i = 0; i < rule_count; i++) {
        sorted_rules[i] = dispatcher->config.rules[i];
    }
    
    // 简单排序（按优先级）
    for (uint32_t i = 0; i < rule_count - 1; i++) {
        for (uint32_t j = i + 1; j < rule_count; j++) {
            if (sorted_rules[i].priority > sorted_rules[j].priority) {
                route_rule_t temp = sorted_rules[i];
                sorted_rules[i] = sorted_rules[j];
                sorted_rules[j] = temp;
            }
        }
    }
    
    // 依次匹配规则
    for (uint32_t i = 0; i < rule_count; i++) {
        const route_rule_t* rule = &sorted_rules[i];
        bool matched = false;
        
        switch (rule->type) {
            case ROUTE_RULE_BY_PROPERTY: {
                // 匹配属性名称
                // 假设JSON格式为: {"properties": {"property1": value1, ...}}
                void* properties = json_utils_get_object_item(json_obj, "properties");
                if (properties != NULL) {
                    // 遍历所有属性
                    // 简化实现：检查属性名称是否匹配
                    const char* prop_name = extract_json_string(properties, rule->pattern);
                    if (prop_name != NULL) {
                        matched = true;
                    } else {
                        // 检查是否有这个属性名
                        void* item = json_utils_get_object_item(properties, rule->pattern);
                        matched = (item != NULL);
                    }
                }
                break;
            }
            
            case ROUTE_RULE_BY_DEVICE_ID: {
                // 匹配设备ID
                const char* device_id = extract_json_string(json_obj, "device_id");
                if (device_id != NULL) {
                    matched = match_pattern(device_id, rule->pattern);
                }
                break;
            }
            
            case ROUTE_RULE_BY_DATA_TYPE: {
                // 匹配数据类型
                const char* data_type = extract_json_string(json_obj, "data_type");
                if (data_type != NULL) {
                    matched = match_pattern(data_type, rule->pattern);
                }
                break;
            }
            
            case ROUTE_RULE_BY_KEYWORD: {
                // 关键字匹配（在JSON字符串中查找）
                const char* json_str = json_utils_print_unformatted(json_obj);
                if (json_str != NULL) {
                    matched = (strstr(json_str, rule->pattern) != NULL);
                    free((void*)json_str);
                }
                break;
            }
        }
        
        if (matched) {
            LOG_DEBUG(LOG_MODULE_NAME, "规则匹配成功: 类型=%d, 模式=%s, 协议=%d",
                     rule->type, rule->pattern, rule->protocol);
            return rule->protocol;
        }
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "未找到匹配的路由规则");
    return DISPATCH_PROTOCOL_MAX;
}

/* ==================== 公开函数实现 ==================== */

dispatcher_handle_t dispatcher_create(const dispatcher_config_t* config) {
    if (config == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置参数为空");
        return NULL;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)calloc(1, sizeof(dispatcher_private_t));
    if (dispatcher == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "内存分配失败");
        return NULL;
    }
    
    // 初始化互斥锁
    if (pthread_mutex_init(&dispatcher->mutex, NULL) != 0) {
        LOG_ERROR(LOG_MODULE_NAME, "互斥锁初始化失败");
        free(dispatcher);
        return NULL;
    }
    
    // 复制配置
    dispatcher->config.rule_count = config->rule_count;
    if (config->rule_count > 0 && config->rules != NULL) {
        size_t rules_size = sizeof(route_rule_t) * config->rule_count;
        dispatcher->config.rules = (route_rule_t*)malloc(rules_size);
        if (dispatcher->config.rules == NULL) {
            LOG_ERROR(LOG_MODULE_NAME, "规则内存分配失败");
            pthread_mutex_destroy(&dispatcher->mutex);
            free(dispatcher);
            return NULL;
        }
        memcpy(dispatcher->config.rules, config->rules, rules_size);
    } else {
        dispatcher->config.rules = NULL;
    }
    
    dispatcher->config.adapter_count = config->adapter_count;
    if (config->adapter_count > 0 && config->adapters != NULL) {
        size_t adapters_size = sizeof(protocol_adapter_t) * config->adapter_count;
        dispatcher->config.adapters = (protocol_adapter_t*)malloc(adapters_size);
        if (dispatcher->config.adapters == NULL) {
            LOG_ERROR(LOG_MODULE_NAME, "适配器内存分配失败");
            free(dispatcher->config.rules);
            pthread_mutex_destroy(&dispatcher->mutex);
            free(dispatcher);
            return NULL;
        }
        memcpy(dispatcher->config.adapters, config->adapters, adapters_size);
        
        // 初始化适配器
        for (uint32_t i = 0; i < config->adapter_count; i++) {
            const protocol_adapter_t* adapter = &config->adapters[i];
            if (adapter->init != NULL && adapter->type < DISPATCH_PROTOCOL_MAX) {
                dispatcher->adapter_handles[adapter->type] = adapter->init(NULL);
                if (dispatcher->adapter_handles[adapter->type] == NULL) {
                    LOG_WARN(LOG_MODULE_NAME, "适配器初始化失败: %s", adapter->name);
                }
            }
        }
    } else {
        dispatcher->config.adapters = NULL;
    }
    
    // 初始化适配器句柄数组
    for (int i = 0; i < DISPATCH_PROTOCOL_MAX; i++) {
        dispatcher->adapter_handles[i] = NULL;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "消息分发器创建成功: 规则数=%u, 适配器数=%u",
             dispatcher->config.rule_count, dispatcher->config.adapter_count);
    
    return (dispatcher_handle_t)dispatcher;
}

void dispatcher_destroy(dispatcher_handle_t handle) {
    if (handle == NULL) {
        return;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)handle;
    
    pthread_mutex_lock(&dispatcher->mutex);
    
    // 清理适配器
    if (dispatcher->config.adapters != NULL) {
        for (uint32_t i = 0; i < dispatcher->config.adapter_count; i++) {
            const protocol_adapter_t* adapter = &dispatcher->config.adapters[i];
            if (adapter->type < DISPATCH_PROTOCOL_MAX &&
                dispatcher->adapter_handles[adapter->type] != NULL &&
                adapter->cleanup != NULL) {
                adapter->cleanup(dispatcher->adapter_handles[adapter->type]);
                dispatcher->adapter_handles[adapter->type] = NULL;
            }
        }
        free(dispatcher->config.adapters);
    }
    
    // 清理规则
    if (dispatcher->config.rules != NULL) {
        free(dispatcher->config.rules);
    }
    
    pthread_mutex_unlock(&dispatcher->mutex);
    
    pthread_mutex_destroy(&dispatcher->mutex);
    free(dispatcher);
    
    LOG_INFO(LOG_MODULE_NAME, "消息分发器已销毁");
}

int dispatcher_dispatch(dispatcher_handle_t handle, const char* data_json) {
    if (handle == NULL || data_json == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "参数为空");
        return -1;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)handle;
    
    // 解析JSON
    void* json_obj = json_utils_parse(data_json);
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "JSON解析失败: %s", data_json);
        return -1;
    }
    
    pthread_mutex_lock(&dispatcher->mutex);
    
    // 匹配路由规则
    dispatch_protocol_type_t protocol = match_route(dispatcher, json_obj);
    
    if (protocol >= DISPATCH_PROTOCOL_MAX) {
        LOG_WARN(LOG_MODULE_NAME, "未找到匹配的协议，数据将被丢弃");
        json_utils_delete(json_obj);
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    // 查找对应的适配器
    protocol_adapter_t* adapter = NULL;
    for (uint32_t i = 0; i < dispatcher->config.adapter_count; i++) {
        if (dispatcher->config.adapters[i].type == protocol) {
            adapter = &dispatcher->config.adapters[i];
            break;
        }
    }
    
    if (adapter == NULL || adapter->send_data == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "未找到协议适配器: %d", protocol);
        json_utils_delete(json_obj);
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    // 获取适配器句柄
    void* adapter_handle = dispatcher->adapter_handles[protocol];
    if (adapter_handle == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "适配器未初始化: %s", adapter->name);
        json_utils_delete(json_obj);
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    pthread_mutex_unlock(&dispatcher->mutex);
    
    // 发送数据到协议
    int result = adapter->send_data(adapter_handle, data_json);
    
    json_utils_delete(json_obj);
    
    if (result == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "数据分发成功: 协议=%d (%s)", protocol, adapter->name);
    } else {
        LOG_ERROR(LOG_MODULE_NAME, "数据分发失败: 协议=%d (%s)", protocol, adapter->name);
    }
    
    return result;
}

int dispatcher_add_rule(dispatcher_handle_t handle, const route_rule_t* rule) {
    if (handle == NULL || rule == NULL) {
        return -1;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)handle;
    
    pthread_mutex_lock(&dispatcher->mutex);
    
    // 扩展规则数组
    uint32_t new_count = dispatcher->config.rule_count + 1;
    route_rule_t* new_rules = (route_rule_t*)realloc(dispatcher->config.rules,
                                                      sizeof(route_rule_t) * new_count);
    if (new_rules == NULL) {
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    new_rules[dispatcher->config.rule_count] = *rule;
    dispatcher->config.rules = new_rules;
    dispatcher->config.rule_count = new_count;
    
    pthread_mutex_unlock(&dispatcher->mutex);
    
    LOG_INFO(LOG_MODULE_NAME, "路由规则已添加: 类型=%d, 模式=%s, 协议=%d",
             rule->type, rule->pattern, rule->protocol);
    
    return 0;
}

int dispatcher_remove_rule(dispatcher_handle_t handle, uint32_t rule_index) {
    if (handle == NULL) {
        return -1;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)handle;
    
    pthread_mutex_lock(&dispatcher->mutex);
    
    if (rule_index >= dispatcher->config.rule_count) {
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    // 移动规则
    for (uint32_t i = rule_index; i < dispatcher->config.rule_count - 1; i++) {
        dispatcher->config.rules[i] = dispatcher->config.rules[i + 1];
    }
    
    dispatcher->config.rule_count--;
    
    pthread_mutex_unlock(&dispatcher->mutex);
    
    LOG_INFO(LOG_MODULE_NAME, "路由规则已移除: 索引=%u", rule_index);
    
    return 0;
}

int dispatcher_register_adapter(dispatcher_handle_t handle, const protocol_adapter_t* adapter) {
    if (handle == NULL || adapter == NULL) {
        return -1;
    }
    
    dispatcher_private_t* dispatcher = (dispatcher_private_t*)handle;
    
    pthread_mutex_lock(&dispatcher->mutex);
    
    // 扩展适配器数组
    uint32_t new_count = dispatcher->config.adapter_count + 1;
    protocol_adapter_t* new_adapters = (protocol_adapter_t*)realloc(dispatcher->config.adapters,
                                                                     sizeof(protocol_adapter_t) * new_count);
    if (new_adapters == NULL) {
        pthread_mutex_unlock(&dispatcher->mutex);
        return -1;
    }
    
    new_adapters[dispatcher->config.adapter_count] = *adapter;
    dispatcher->config.adapters = new_adapters;
    dispatcher->config.adapter_count = new_count;
    
    // 初始化适配器
    if (adapter->init != NULL && adapter->type < DISPATCH_PROTOCOL_MAX) {
        dispatcher->adapter_handles[adapter->type] = adapter->init(NULL);
        if (dispatcher->adapter_handles[adapter->type] == NULL) {
            LOG_WARN(LOG_MODULE_NAME, "适配器初始化失败: %s", adapter->name);
        }
    }
    
    pthread_mutex_unlock(&dispatcher->mutex);
    
    LOG_INFO(LOG_MODULE_NAME, "协议适配器已注册: %s (类型=%d)", adapter->name, adapter->type);
    
    return 0;
}
